package com.dense.kuiniu.shelfcard.card.iccard;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.SPUtils;
import com.dense.kuiniu.shelfcard.base.SpKey;
import com.dense.kuiniu.shelfcard.base.Url;
import com.dense.kuiniu.shelfcard.card.idcard.IDCardInfo;
import com.dense.kuiniu.shelfcard.entity.BindInfo;

import java.lang.ref.WeakReference;

import io.reactivex.rxjava3.functions.Consumer;
import rxhttp.RxHttp;

/**
 * @author Administrator
 * @date 2021/3/4
 * 将卡与身份证绑定
 */
public class KNCardBinder implements ICardBinder {
    private final Object mLock = new Object();
    private IDCardInfo mIDCardInfo;
    private WeakReference<BindObserver> mReference;
    private BindInfo mBindInfo;
    private String mErrorInfo;

    public KNCardBinder(IDCardInfo IDCardInfo, BindObserver observer) {
        mIDCardInfo = IDCardInfo;
        mReference = new WeakReference<>(observer);
    }

    @Override
    public boolean bindCard(String cardNo) {
        bindToServer(mIDCardInfo, cardNo);
        synchronized (mLock) {
            try {
                mLock.wait(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (mReference.get() != null) {
            if (mBindInfo != null) {
                mReference.get().succeed(mBindInfo);
            } else {
                mReference.get().failed(mErrorInfo);
            }
        }
        return mBindInfo != null;
    }

    private void bindToServer(IDCardInfo idCardInfo, String icCardNo) {
        RxHttp.postJson(Url.bindCard)
                .add("deviceId", DeviceUtils.getAndroidID())
                .add("fkReaderName", idCardInfo.getName())
                .add("idcard", idCardInfo.getCardNo())
                .add("libraryCode", SPUtils.getInstance().getString(SpKey.KEY_BINDING_LIBRARY))
                .add("newCardNumber", icCardNo)
                .asResponse(BindInfo.class)
                .subscribe(new Consumer<BindInfo>() {
                    @Override
                    public void accept(BindInfo info) throws Throwable {
                        mBindInfo = info;
                        synchronized (mLock) {
                            mLock.notify();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        mErrorInfo = throwable.getMessage();
                        synchronized (mLock) {
                            mLock.notify();
                        }
                    }
                });
    }

    public static interface BindObserver {
        public void succeed(BindInfo info);

        public void failed(String msg);
    }
}